package com.company.management.config;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.company.management.modal.entity.User;
import com.company.management.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

//@Configuration
//@EnableScheduling
@Slf4j
public class SchedulerConfig  implements SchedulingConfigurer  {
   @Resource
    UserService userService;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
            ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
            taskScheduler.setPoolSize(10); // 设置线程池大小
            taskScheduler.setThreadNamePrefix("Scheduled-Thread-"); // 设置线程名称前缀
            taskScheduler.initialize(); // 初始化线程池
            // 将自定义的 TaskScheduler 设置到任务注册器中
            taskRegistrar.setTaskScheduler(taskScheduler);

        taskRegistrar.addTriggerTask(
                () -> performTask(),
                triggerContext -> {
                     //*/5 * * * * ?
                    return new CronTrigger("0 0 0 1 * ?").nextExecutionTime(triggerContext);
                }
        );

    }
    public void performTask() {
        log.info("定时任务执行中{}...", LocalDateTime.now());
        List<User> userList = new ArrayList<>();
        userService.listAll().stream().forEach(userdto -> {
            User user = new User();
            userdto.setScore(100);
            BeanUtils.copyProperties(userdto, user);
            userList.add(user);
        });
        if (CollectionUtils.isNotEmpty(userList)) {
            userService.batchUpdateUsers(userList);
        }
    }
}
